/*
 * @Description:
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2023-04-30 12:22:02
 * @LastEditors: swc
 * @LastEditTime: 2025-01-22 15:37:57
 */
import { Tsrv } from '@/services/index';
import ViewUI from 'view-design';
import Vue from 'vue';
import { NavigationGuardNext, Route } from 'vue-router';
import router from './index';

const loginRouterPath = Tsrv.lexicon.routerPath.login.path;
const rootRouterPath = Tsrv.lexicon.routerPath.root.path;
const singleSignRouterPath = Tsrv.lexicon.routerPath.singleSign.path;
const headTitle = Tsrv.lexicon.headTitle;
Vue.use(ViewUI);

const storeSysInfo = async (key: string = null): Promise<boolean> => {
  const [resp, err] = await Tsrv.getSysInfo(key);
  if (err) {
    console.error('获取系统信息失败');
    Vue.prototype.$msg('-50013,FE,90');
    Tsrv.cookies.removeCookies;
    return false;
  }
  if (!resp.success) {
    Vue.prototype.$msg(resp.msg);
    Tsrv.cookies.removeCookies;
    return false;
  }
  const ok = await Tsrv.getStore().dispatch('setSysInfo', resp.data);
  !ok && console.error('获取系统信息失败');
  return ok;
};

const delLoadNode = (): Promise<void> => {
  // 删除起动load节点
  const loading = document.querySelector('#loading-layer') as HTMLDivElement;
  return new Promise(resolve => {
    if (loading) {
      loading.style.opacity = '0';
      setTimeout(() => {
        document.body.removeChild(loading);
        resolve();
      }, 50);
    } else {
      resolve();
    }
  });
};

router.beforeEach((to: Route, from: Route, next: NavigationGuardNext) => {
  const token: string = Tsrv.cookies.getToken();
  document.title = headTitle;
  if (to.path === loginRouterPath) {
    next();
  } else if (to.path === rootRouterPath) {
    if (!Tsrv.utils.noValue(to.query)) {
      if (to.query?.app) {
        const p = to.query.app.toString().split(`,`);
        let _p = '';
        p.forEach(e => {
          if (_p === '') {
            _p = e;
          } else {
            _p = `${_p}&${e}`;
          }
        });
        const nextPath = `${singleSignRouterPath}?${_p}`;
        next(nextPath);
      } else {
        next('*');
      }
    } else if (token === 'undefined') {
      next(loginRouterPath);
    } else {
      delLoadNode().then(e => {
        Vue.prototype.$Loading.start();
        storeSysInfo().then(ok => {
          Vue.prototype.$Loading.finish();
          if (ok) {
            next();
          } else {
            next(loginRouterPath);
          }
        });
      });
    }
  } else if (to.path === singleSignRouterPath) {
    next();
    // const key = to.query?.key as string;
    // if (Tsrv.noValue(key)) {
    //   alert(Tsrv.getI18nByValue('请输入key'));
    // }
    // Tsrv.standardGetReq<ifs.I_restFulRes, any>(
    //   { key },
    //   Tsrv.lexicon.url.getToken
    // )
    //   .then(([res, err]) => {
    //     if (!Tsrv.utils.noValue(err) || res.code !== 200) {
    //       console.error('获取token失败');
    //     } else {
    //       Tsrv.getStore()
    //         .dispatch('Login', {
    //           userID: res.data.userID,
    //           userNo: res.data.userNo,
    //           userName: res.data.userName,
    //           dbName: res.data.dbName,
    //           token: res.data.token
    //         })
    //         .then(() => {
    //           Vue.prototype.$Loading.start();
    //           storeSysInfo(key).then(ok => {
    //             Vue.prototype.$Loading.finish();
    //             if (ok) {
    //               next();
    //             }
    //           });
    //         });
    //     }
    //   })
    //   .catch(e => {
    //     console.error('获取token错误');
    //   });
  } else {
    Vue.prototype.$Loading.start();
    storeSysInfo().then(ok => {
      Vue.prototype.$Loading.finish();
      if (ok) {
        next();
      }
    });
    // next();
  }
});
router.afterEach((to: Route, from: Route) => {
  if (to.name === Tsrv.lexicon.routerPath.page404.name) {
    delLoadNode();
  }
});
